<template>
  <div class="schedule-calendar-container">
    <div class="header">
      <h2>班次日历</h2>
      <div class="filter-container">
        <el-select v-model="selectedProduct" placeholder="按产品筛选" clearable @change="filterByProduct" class="product-filter">
          <el-option
            v-for="product in productOptions"
            :key="product"
            :label="product"
            :value="product"
          />
        </el-select>
      </div>
    </div>

    <div class="calendar-container">
      <div class="calendar-header">
        <el-button class="nav-button" @click="prevPeriod">
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
        <h3>{{ currentPeriodLabel }}</h3>
        <el-button class="nav-button" @click="nextPeriod">
          <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>

      <!-- 月视图 -->
      <div class="month-view">
        <div class="weekdays">
          <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
        </div>
        <div class="days-grid">
          <div
            v-for="(day, index) in calendarDays"
            :key="index"
            class="day-cell"
            :class="{ 'current-month': day.currentMonth, 'today': day.isToday }"
          >
            <div class="day-number">{{ day.date.getDate() }}</div>
            <div class="schedules-container">
              <div
                v-for="schedule in getSchedulesForDay(day.date)"
                :key="schedule.id"
                class="schedule-item"
                :style="{ backgroundColor: getShiftColor(schedule.shift_id) }"
                @click="showScheduleDetails(schedule)"
              >
                {{ getEmployeeName(schedule.employee_id) }} - {{ getShiftName(schedule.shift_id) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 排班详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="排班详情"
      width="500px"
      class="schedule-dialog"
    >
      <div v-if="selectedSchedule" class="schedule-details">
        <p><strong>员工:</strong> <span>{{ getEmployeeName(selectedSchedule.employee_id) }}</span></p>
        <p><strong>班次:</strong> <span>{{ getShiftName(selectedSchedule.shift_id) }}</span></p>
        <p><strong>产品:</strong> <span>{{ getShiftProduct(selectedSchedule.shift_id) }}</span></p>
        <p><strong>日期:</strong> <span>{{ formatDate(selectedSchedule.date) }}</span></p>
        <p><strong>时间:</strong> <span>{{ formatShiftTime(selectedSchedule.shift_id) }}</span></p>
        <p><strong>状态:</strong> <span class="status-tag" :class="getStatusClass(selectedSchedule.status)">{{ selectedSchedule.status }}</span></p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="editSchedule">编辑</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useScheduleStore } from '../stores/schedule.js'
import { ElMessage } from 'element-plus'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'

const router = useRouter()
const store = useScheduleStore()

// 状态变量
const loading = ref(false)
const currentDate = ref(new Date())
const selectedProduct = ref('')
const dialogVisible = ref(false)
const selectedSchedule = ref(null)

// 计算属性
const employees = computed(() => store.employees)
const shifts = computed(() => store.shifts)
const schedules = computed(() => {
  if (!selectedProduct.value) {
    return store.schedules
  }
  
  // 根据产品筛选排班
  return store.schedules.filter(schedule => {
    const shift = shifts.value.find(s => s.ID === schedule.shift_id)
    return shift && shift.product_name === selectedProduct.value
  })
})

// 产品选项
const productOptions = computed(() => {
  const products = new Set()
  shifts.value.forEach(shift => {
    if (shift.product_name) {
      products.add(shift.product_name)
    }
  })
  return Array.from(products)
})

// 日历相关计算属性
const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

// 当前周期标签（月份）
const currentPeriodLabel = computed(() => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth() + 1
  return `${year}年${month}月`
})

// 月视图的日历天数
const calendarDays = computed(() => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth()
  
  // 当月第一天
  const firstDay = new Date(year, month, 1)
  // 当月最后一天
  const lastDay = new Date(year, month + 1, 0)
  
  // 当月第一天是星期几
  const firstDayOfWeek = firstDay.getDay()
  
  // 需要显示的上个月的天数
  const prevMonthDays = firstDayOfWeek
  
  // 需要显示的下个月的天数
  const daysInMonth = lastDay.getDate()
  const totalCells = 42 // 6行7列
  const nextMonthDays = totalCells - daysInMonth - prevMonthDays
  
  const days = []
  
  // 上个月的日期
  const prevMonth = new Date(year, month - 1, 0)
  const prevMonthLastDay = prevMonth.getDate()
  
  for (let i = prevMonthDays - 1; i >= 0; i--) {
    const date = new Date(year, month - 1, prevMonthLastDay - i)
    days.push({
      date,
      currentMonth: false,
      isToday: isSameDay(date, new Date())
    })
  }
  
  // 当月的日期
  for (let i = 1; i <= daysInMonth; i++) {
    const date = new Date(year, month, i)
    days.push({
      date,
      currentMonth: true,
      isToday: isSameDay(date, new Date())
    })
  }
  
  // 下个月的日期
  for (let i = 1; i <= nextMonthDays; i++) {
    const date = new Date(year, month + 1, i)
    days.push({
      date,
      currentMonth: false,
      isToday: isSameDay(date, new Date())
    })
  }
  
  return days
})

// 方法
const prevPeriod = () => {
  const newDate = new Date(currentDate.value)
  newDate.setMonth(newDate.getMonth() - 1)
  currentDate.value = newDate
}

const nextPeriod = () => {
  const newDate = new Date(currentDate.value)
  newDate.setMonth(newDate.getMonth() + 1)
  currentDate.value = newDate
}

const getSchedulesForDay = (date) => {
  return schedules.value.filter(schedule => {
    const scheduleDate = new Date(schedule.date)
    return isSameDay(scheduleDate, date)
  })
}

const isSameDay = (date1, date2) => {
  return date1.getFullYear() === date2.getFullYear() &&
         date1.getMonth() === date2.getMonth() &&
         date1.getDate() === date2.getDate()
}

const showScheduleDetails = (schedule) => {
  selectedSchedule.value = schedule
  dialogVisible.value = true
}

const editSchedule = () => {
  if (selectedSchedule.value) {
    router.push({
      path: '/schedule',
      query: { scheduleId: selectedSchedule.value.ID }
    })
  }
}

const filterByProduct = () => {
  // 产品过滤已通过计算属性实现
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString()
}

const formatShiftTime = (shiftId) => {
  const shift = shifts.value.find(s => s.ID === shiftId)
  if (!shift) return ''
  
  if (shift.is_full_day) return '全天'
  
  const startTime = new Date(shift.start_time)
  const endTime = new Date(shift.end_time)
  
  return `${startTime.getHours()}:${startTime.getMinutes().toString().padStart(2, '0')} - ${endTime.getHours()}:${endTime.getMinutes().toString().padStart(2, '0')}`
}

const getEmployeeName = (employeeId) => {
  const employee = employees.value.find(e => e.ID === employeeId)
  return employee ? employee.name : ''
}

const getShiftName = (shiftId) => {
  const shift = shifts.value.find(s => s.ID === shiftId)
  return shift ? shift.name : ''
}

const getShiftProduct = (shiftId) => {
  const shift = shifts.value.find(s => s.ID === shiftId)
  return shift ? shift.product_name || '无产品' : '无产品'
}

// 根据班次ID获取颜色
const getShiftColor = (shiftId) => {
  if (!shiftId) return 'rgba(0, 102, 204, 0.8)'
  
  const shift = shifts.value.find(s => s.ID === shiftId)
  if (!shift) return 'rgba(0, 102, 204, 0.8)'
  
  // 使用班次ID生成颜色
  const hash = shiftId.toString().split('').reduce((acc, char) => {
    return char.charCodeAt(0) + ((acc << 5) - acc)
  }, 0)
  
  // 预定义的颜色数组 - 使用更柔和的苹果风格颜色
  const colors = [
    'rgba(0, 102, 204, 0.85)',   // 蓝色
    'rgba(52, 199, 89, 0.85)',   // 绿色
    'rgba(255, 159, 10, 0.85)',  // 橙色
    'rgba(175, 82, 222, 0.85)',  // 紫色
    'rgba(255, 45, 85, 0.85)',   // 粉色
    'rgba(90, 200, 250, 0.85)',  // 青色
    'rgba(0, 199, 190, 0.85)',   // 蓝绿色
    'rgba(88, 86, 214, 0.85)',   // 深紫色
    'rgba(76, 217, 100, 0.85)',  // 浅绿色
    'rgba(255, 69, 58, 0.85)',   // 红色
    'rgba(255, 204, 0, 0.85)',   // 黄色
    'rgba(142, 142, 147, 0.85)'  // 灰色
  ]
  
  // 使用哈希值选择颜色
  const index = Math.abs(hash) % colors.length
  return colors[index]
}

// 根据状态获取样式类
const getStatusClass = (status) => {
  if (!status) return ''
  
  switch(status.toLowerCase()) {
    case '已确认':
    case '已完成':
      return 'status-success'
    case '待确认':
    case '待处理':
      return 'status-warning'
    case '已取消':
    case '已拒绝':
      return 'status-danger'
    default:
      return 'status-info'
  }
}

// 初始化
onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      store.fetchEmployees(),
      store.fetchShifts(),
      store.fetchSchedules()
    ])
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.schedule-calendar-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
  color: var(--apple-text-color);
}

.filter-container {
  display: flex;
  gap: 16px;
  align-items: center;
}

.product-filter {
  min-width: 180px;
}

.calendar-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: var(--apple-card-bg);
  border-radius: var(--apple-radius-lg);
  box-shadow: var(--apple-shadow-sm);
  border: 1px solid var(--apple-border-color);
  overflow: hidden;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  padding: 16px;
  border-bottom: 1px solid var(--apple-border-color);
  background-color: var(--apple-table-header-bg);
}

.calendar-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: var(--apple-text-color);
}

/* 月视图样式 */
.month-view {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.weekdays {
  display: flex;
  border-bottom: 1px solid var(--apple-border-color);
}

.weekday {
  flex: 1;
  text-align: center;
  padding: 12px;
  font-weight: 500;
  color: var(--apple-secondary-text);
  background-color: var(--apple-table-header-bg);
}

.days-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-template-rows: repeat(6, 1fr);
  overflow: auto;
}

.day-cell {
  border-right: 1px solid var(--apple-border-color);
  border-bottom: 1px solid var(--apple-border-color);
  padding: 8px;
  min-height: 100px;
  position: relative;
  background-color: var(--apple-card-bg);
  transition: background-color 0.2s ease;
}

.day-cell:not(.current-month) {
  background-color: var(--apple-table-hover);
  color: var(--apple-secondary-text);
}

.day-cell.today {
  background-color: rgba(0, 102, 204, 0.05);
}

.day-cell:hover {
  background-color: var(--apple-hover-bg);
}

.day-number {
  font-weight: 500;
  margin-bottom: 8px;
  color: var(--apple-text-color);
}

.day-cell:not(.current-month) .day-number {
  color: var(--apple-secondary-text);
  opacity: 0.7;
}

.schedules-container {
  display: flex;
  flex-direction: column;
  gap: 4px;
  overflow: auto;
  max-height: calc(100% - 30px);
  padding: 2px;
}

.schedule-item {
  padding: 6px 8px;
  border-radius: var(--apple-radius-sm);
  font-size: 12px;
  color: white;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  box-shadow: var(--apple-shadow-sm);
  transition: transform 0.2s ease, box-shadow 0.2s ease, opacity 0.2s ease;
  backdrop-filter: blur(4px);
  font-weight: 500;
  letter-spacing: 0.2px;
  border: 0.5px solid rgba(255, 255, 255, 0.2);
}

.schedule-item:hover {
  transform: translateY(-1px);
  box-shadow: var(--apple-shadow-md);
  opacity: 0.95;
}

.schedule-dialog :deep(.el-dialog__header) {
  padding: 16px 20px;
  border-bottom: 1px solid var(--apple-border-color);
}

.schedule-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.schedule-dialog :deep(.el-dialog__footer) {
  padding: 16px 20px;
  border-top: 1px solid var(--apple-border-color);
}

.schedule-details {
  padding: 8px 0;
}

.schedule-details p {
  margin: 12px 0;
  line-height: 1.6;
  color: var(--apple-text-color);
  display: flex;
  align-items: center;
}

.schedule-details strong {
  color: var(--apple-secondary-text);
  font-weight: 500;
  min-width: 60px;
  margin-right: 8px;
}

.schedule-details span {
  color: var(--apple-text-color);
}

.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-success {
  background-color: rgba(52, 199, 89, 0.1);
  color: var(--apple-success-color);
  border: 1px solid rgba(52, 199, 89, 0.2);
}

.status-warning {
  background-color: rgba(255, 159, 10, 0.1);
  color: var(--apple-warning-color);
  border: 1px solid rgba(255, 159, 10, 0.2);
}

.status-danger {
  background-color: rgba(255, 59, 48, 0.1);
  color: var(--apple-danger-color);
  border: 1px solid rgba(255, 59, 48, 0.2);
}

.status-info {
  background-color: rgba(0, 102, 204, 0.1);
  color: var(--apple-primary-color);
  border: 1px solid rgba(0, 102, 204, 0.2);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .product-filter {
    width: 100%;
  }
  
  .day-cell {
    min-height: 80px;
    padding: 4px;
  }
  
  .schedule-item {
    padding: 2px 4px;
    font-size: 10px;
  }
}
</style>